package com.hspedu.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.seckill.mapper.UserMapper;
import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.utils.CookieUtil;
import com.hspedu.seckill.utils.MD5Util;
import com.hspedu.seckill.utils.UUIDUtil;
import com.hspedu.seckill.vo.LoginVo;
import com.hspedu.seckill.vo.RespBean;
import com.hspedu.seckill.vo.RespBeanEnum;
import com.hspedu.seckill.vo.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    //登录id为手机号
    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        if(!StringUtils.hasText(mobile) || !StringUtils.hasText(password)){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        if(!ValidatorUtil.isMobile(mobile)){
            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        }

        User user = userMapper.selectById(mobile);
        if (user == null) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        if (!MD5Util.midPassToDBPass(password, user.getSlat()). equals(user.getPassword())) {
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }

        //这里做后续优化
        String ticket = UUIDUtil.uuid();

/*        //将登陆成功的用户保存到Session
        request.getSession().setAttribute(ticket,user);*/

        //登录用户存入redis
        redisTemplate.opsForValue().set("user:" + ticket, user);

        //将ticket存到cookie
        CookieUtil.setCookie(request,response,"userTicket",ticket);
        return RespBean.success(ticket);

    }

    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {

        if (!StringUtils.hasText(userTicket)){
            return null;
        }

        User user= (User) redisTemplate.opsForValue().get("user:" + userTicket);

        //用户不为null,就重新设置cookie，刷新(cookie生命周期30分钟，刷新一下重新刷新生命周期)
        if (user!=null){
            CookieUtil.setCookie(request,response,"userTicket",userTicket);
        }

        return user;
    }
}
